package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 品牌
 *
 * @author wenchao.long
 * @email wenchao.long@gmail.com
 * @date 2021-06-12 22:51:26
 */
@Service("brandService")
@AllArgsConstructor
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    private final CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                Wrappers.<BrandEntity>lambdaQuery()
                        .eq(Func.isNoneBlank(key), BrandEntity::getBrandId, key)
                        .or()
                        .like(Func.isNotBlank(key), BrandEntity::getName, key)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段的数据一直
        updateById(brand);
        String name = brand.getName();
        if (Func.isNoneBlank(name)) {
            categoryBrandRelationService.update(Wrappers.<CategoryBrandRelationEntity>lambdaUpdate()
                    .set(CategoryBrandRelationEntity::getBrandName, name)
                    .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId())
            );

            // TODO 更新其他关联
        }
    }
}
